package com.github.cyf.ip2region;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.lionsoul.ip2region.xdb.Searcher;
import org.springframework.util.ResourceUtils;

import java.io.FileNotFoundException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author chenyifan
 * @create 2025-02-10 15:15
 */
@Slf4j
public class AddressUtil {

    private static final String DEFAULT_CITY_NAME = "未知";

    private static final String DB_PATH;

    static {
        try {
            DB_PATH = ResourceUtils.getFile("classpath:ip2region/ip2region.xdb").getAbsolutePath();
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 获取城市信息
     * @param ip
     * @return
     */
    public static String getIpAddress(String ip) {
        if ("127.0.0.1".equals(ip) || ip.startsWith("192.168")) {
            return "内网IP";
        }
        try {
            Searcher searcher = Searcher.newWithFileOnly(DB_PATH);
            List<String> list = Arrays.stream(searcher.searchByStr(ip).split("\\|")).filter(s -> !"0".equals(s)).collect(Collectors.toList());
            return StringUtils.join(list, ",");
        } catch (Exception e) {
            e.printStackTrace();
            return DEFAULT_CITY_NAME;
        }
    }

    public static void main(String[] args) {
        String ip = "12.3.23.4";
        String cityIpString = getIpAddress(ip);
        System.out.println(cityIpString);
    }
}